package com.chasmcity.munrobagging.map;

import static java.util.Collections.*;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;

import com.chasmcity.munrobagging.MunroBaggingApp;
import com.chasmcity.munrobagging.R;
import com.chasmcity.munrobagging.map.ImprovedMapView.MapMovementListener;
import com.chasmcity.munrobagging.model.LatLongBoundingBox;
import com.chasmcity.munrobagging.model.Munro;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: Missing class description for MunroOverlay!
 * <p>
 * &copy; Copyright 2011 Kizoom Ltd.
 * <p>
 * $Id: wildebeest_standard.epf,v 1.9 2007/01/17 14:59:59 danf Exp $
 */
public class MunroOverlay extends ItemizedOverlay<OverlayItem> implements MapMovementListener {
	
	private final Context context;
	private final int minimumZoomLevel;
	private final List<Munro> munros;
	private List<MunroMarker> markers = emptyList();

	public MunroOverlay(Context context) {
		super(boundCenterBottom(context.getResources().getDrawable(R.drawable.pin)));
		this.munros = MunroBaggingApp.getMunros(context);
		this.context = context;
		this.minimumZoomLevel = context.getResources().getInteger(R.integer.minimumMarkerZoomLevel);
		populate();
	}
	
	@Override
	protected MunroMarker createItem(int index) {
		return markers.get(index);
	}

	@Override
	public int size() {
		return markers.size();
	}
	
	@Override
	public void mapMoved(LatLongBoundingBox newBoundingBox, int newZoomLevel) {
		List<MunroMarker> newMarkers = new ArrayList<MunroMarker>();
		
		if (newZoomLevel >= minimumZoomLevel) {
			for (Munro munro : munros) {
				if (newBoundingBox.encloses(munro.getLatLong())) {
					newMarkers.add(new MunroMarker(munro));
				}
			}
		}
		Log.i("MunroOverlay", "Displaying " + newMarkers.size() + " out of " + munros.size() + " munros");
		markers = newMarkers;
		setLastFocusedIndex(-1);
		populate();
	}
	
	@Override
	protected boolean onTap(int index) {
		MunroMarker marker = markers.get(index);
		
		new AlertDialog.Builder(context)
			.setMessage(marker.getTitle())
			.setNeutralButton("OK", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			})
			.create().show();
		
		return true;
	}
	
	public class MunroMarker extends OverlayItem {
		public MunroMarker(Munro munro) {
			super(munro.getLatLong().asGeoPoint(), munro.getName(), munro.getName());
		}
	}
}
